
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel","selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel,
        selectInput = layui.selectInput;

    let priceTermsList = [];
    let operationList=[];
    let salesmanList=[];
    let deptSalesmanList = [];
    let deptOperationList=[];
    
    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    //客户名称
    let ins = selectInput.render({
        elem: '#customerSelect',
        name: 'customerSelect',
        hasSelectIcon: true,
        placeholder: '请输入名称',
        data: [],
    })
    let customerInfo = [];
    //监听输入
    ins.on('itemInput(customerSelect)', function (obj) {
        let tempData = [];
        $.ajax({
            url: "basicInformation/getCustomerInfo?info=" + obj.value,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    customerInfo = res.data.customerInfo;
                    for (let i in customerInfo) {
                        customerInfo[i]["value"] = customerInfo[i].code;
                        tempData.push(customerInfo[i]);
                    }
                }
            }
        })
        ins.addSelect(tempData)
    })

    // 监听select 选择事件
    ins.on('itemSelect(customerSelect)', function (obj) {
        let code = obj.data;
        $("#customerCode").val(code);
    });

    layer.ready(function () {
        //获取所有公司信息
        $.ajax({
            url: "receivePayment/getCompanyInfo",
            success: function (data) {
                if (data.status == 200) {
                    for (let i in data.data) {
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取业务模式信息
        $.ajax({
            url:"offer/getBusinessModel",
            success:function(data){
                if(data.status == 200){
                    for(let i in data.data){
                        $('#businessMode').append(new Option(data.data[i].name, data.data[i].name));
                    }
                    form.render('select');
                }
            }
        });

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList=getxmselect("#operationCode", "operationCode", userTree);
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", userTree);
        } else {
            operationList=getxmselect("#operationCode", "operationCode", [{name: user.name, value: user.code}])
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}]);
        }


        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        } else {
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }


        //获取价格术语信息
        $.ajax({
            url:"offer/getPriceTerms",
            success:function(data){
                if(data.status == 200){
                    let priceTermsData = [];
                    for(let i in data.data){
                        let tmp = {
                            name:data.data[i].name,
                            value:data.data[i].name
                        }
                        priceTermsData.push(tmp);
                    }
                    priceTermsList = getxmselect("#priceTermsCode", "priceTermsCode", priceTermsData);
                    form.render('select');
                }
            }
        });

    });
    form.render();//表单刷新

    let initData = [];
    table.render({
        elem: '#offerselect'
        , data: initData
        , where: {operationCode: user.code}
        , url: 'receivePayment/statistics/getProfitStatisticsInfoByPage'
        , toolbar: '#offertoolbar'
        ,totalRow: true
        , cols: [[
            //以结汇主表为主
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            ,{field: 'companyName', title: '制单公司', sort: true, width: 220, event: "quotationno"}
            , {field: 'invoiceNo', title: '发票号', sort: true, width: 120}
            , {field: 'invoiceDate', title: '发票日期', sort: true, width: 120}
            , {field: 'contractNo', title: '外销合同号', sort: true, width: 120}
            , {field: 'letNo', title: '批次', sort: true, width: 220}
            , {field: 'carryDate', title: '出运日期', sort: true, width: 120}
            , {field: 'createTime', title: '制单日期', sort: true, width: 120}
            , {field: 'salesman', title: '业务员', sort: true, width: 120}
            , {field: 'customerName', title: '客户名称', sort: true, width: 120}
            , {field: 'priceTerm', title: '价格术语', sort: true, width: 120}
            , {field: 'businessModeName', title: '业务模式', sort: true, width: 120}
            , {field: 'moneyKind', title: '币种', sort: true, width: 120}
            , {field: 'invoiceMoney', title: '应收货款', sort: true, width: 180, totalRow: true}
            , {field: 'receivableRmb', title: '应收折人民币', sort: true, width: 180, totalRow: true}
            , {field: 'receivableUsd', title: '应收货款(USD)', sort: true, width: 180, totalRow: true}
            , {field: 'productTotalPrice', title: '产品金额小计', sort: true, width: 180, totalRow: true}
            , {field: 'costMoneyOfRmb', title: '应收结汇费用(RMB)', sort: true, width: 180, totalRow: true}
            , {field: 'costMoneyOfUsd', title: '应收结汇费用(USD)', sort: true, width: 180, totalRow: true}
            , {field: 'costDesc', title: '应收费用备注', sort: true, width: 180}
            , {field: 'collectionAmount', title: '实收货款', sort: true, width: 180, totalRow: true}
            , {field: 'collectionAmountUsd', title: '实收货款(USD)', sort: true, width: 180, totalRow: true}
            , {field: 'collectionAmountRmb', title: '实收折人民币', sort: true, width: 180, totalRow: true}
            , {field: 'unCollectionAmountUsd', title: '未收货款(USD)', sort: true, width: 180, totalRow: true}
            , {field: 'unCollectionAmountRmb', title: '未收折人民币', sort: true, width: 180, totalRow: true}
            , {field: 'foreignBankDeductions', title: '银行扣费', sort: true, width: 180, totalRow: true}
            , {field: 'foreignBankDeductionsRmb', title: '银行扣费折人民币', sort: true, width: 180, totalRow: true}
            , {field: 'claimSalesman', title: '认领业务员', width: 220}
            , {field: 'costSubtotalSum', title: '应付货款', sort: true, width: 180, totalRow: true}
            , {field: 'actuallyAmount', title: '已付货款', sort: true, width: 180, totalRow: true}
            , {field: 'unActuallyAmount', title: '未付货款', sort: true, width: 180, totalRow: true}
            , {field: 'applicationAmountCost', title: '已付费用', sort: true, width: 180, totalRow: true}
            , {field: 'openedAmount', title: '已开票金额', sort: true, width: 180, totalRow: true}
            , {field: 'applicationAmountUSD', title: '费用小计(USD)', sort: true, width: 180, totalRow: true}
            , {field: 'applicationAmountRMB', title: '费用小计(RMB)', sort: true, width: 180, totalRow: true}
            , {field: 'applicationAmountSUM', title: '费用合计(RMB)', sort: true, width: 180, totalRow: true}
            , {field: 'transferCostSum', title: '运费', sort: true, width: 180, totalRow: true}
            , {field: 'tariffSum', title: '关税', sort: true, width: 180, totalRow: true}
            , {field: 'storageOperationFee', title: '美国仓储操作费', sort: true, width: 180, totalRow: true}
            , {field: 'warehouseFee', title: '海外仓储费用', sort: true, width: 180, totalRow: true}
            , {field: 'commission', title: '佣金', sort: true, width: 180, totalRow: true}
            , {field: 'freightForwardingFee', title: '货运代理费', sort: true, width: 180, totalRow: true}
            , {field: 'otherFee', title: '其他相关费用', sort: true, width: 180, totalRow: true}
            , {field: 'theoreticalTaxRefund', title: '预计退税', sort: true, width: 180, totalRow: true}
            , {field: 'actualTaxRefund', title: '实际退税', sort: true, width: 180, totalRow: true}
            , {field: 'estimatedGrossProfit', title: '预计毛利润（RMB)', sort: true, width: 180, totalRow: true}
            , {field: 'profitMargin', title: '预计毛利润率(不含费用)%', sort: true, width: 180, totalRow: true}
            , {field: 'profitMarginDirectCost', title: '预计毛利润率(含直接费用)%', sort: true, width: 180, totalRow: true}
        ]]
        , id: 'offertableid'
        , height: $(document).height() - $('#offerselect').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
    });

    /*table.on('tool(offertable)', function(obj){
        let data = obj.data;
        let id = data.id;
        if (obj.event === "quotationno"){
            parent.intab("views/jsp/ExportBusiness/tpl/viewexport.jsp?id="+id,"外销明细")
        }
    });*/


    form.on('submit(submitform)', function (data) {
        table.reload('offertableid', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: data.field
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"receivePayment/export/getContractStatisticsFQExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 120,
                        'AQ': 120
                    }, 120);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, 'FQ利润统计表.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    document.getElementById('clear').onclick = function(){
        operationList.setValue([ ]);
        salesmanList.setValue([ ]);
        priceTermsList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
        deptOperationList.setValue([ ]);
    };
});